﻿using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace AutoCADDotNetLibrary.Generator.Receiver
{
    public class IExtensionApplicationSyntaxReceiver : ISyntaxContextReceiver
    {
        public List<ITypeSymbol> Types { get; } = new List<ITypeSymbol>();

        private ITypeSymbol _extensionApplicationAttributeValue;
        public void OnVisitSyntaxNode(GeneratorSyntaxContext context)
        {
            //得到[assembly: ExtensionApplication(Type)]参数值
            if (_extensionApplicationAttributeValue == null)
            {
                ImmutableArray<AttributeData> atts = context.SemanticModel.Compilation.Assembly.GetAttributes();
                foreach (AttributeData att in atts)
                {
                    if (att.AttributeClass.ToDisplayString() == "Autodesk.AutoCAD.Runtime.ExtensionApplicationAttribute")
                    {
                        _extensionApplicationAttributeValue = att.ConstructorArguments[0].Value as ITypeSymbol;
                    }
                }
            }

            //得到继承自IExtensionApplication的类型
            if (context.Node is ClassDeclarationSyntax classDeclarationSyntax)
            {
                //得到语义
                ITypeSymbol classSymbol = context.SemanticModel.GetDeclaredSymbol(classDeclarationSyntax) as ITypeSymbol;

                //没值时，得到具体类型
                if (classSymbol.Interfaces.Any(ad => ad.ToDisplayString() == "Autodesk.AutoCAD.Runtime.IExtensionApplication")
                   && !(_extensionApplicationAttributeValue != null && _extensionApplicationAttributeValue.Equals(classSymbol, SymbolEqualityComparer.Default)))
                {
                    Types.Add(classSymbol);
                }
            }
        }
    }
}
